package com.yc.book;

import com.yc.book.util.Utils;
import com.yc.common.bean.Result;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;

@MultipartConfig

@WebServlet(name = "UploadServlet", value = "/upload")

public class UploadServlet extends HttpServlet {
    private String uploadDir = "D:\\imagesss\\";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Result res;
        try {
            Part part = request.getPart("file");
            String diskpath = uploadDir + part.getSubmittedFileName();
            String webpath = "upload/" + part.getSubmittedFileName();
            File file = new File(diskpath);
            if (!file.exists()) {
                part.write(diskpath);
            }
            res = Result.success("文件上传成功", webpath);
        } catch (Exception e) {
            e.printStackTrace();
            res = Result.failure("文件上传失败", null);
        }

        System.out.println(res.getData() + " " + res.getMsg());
        Utils.writeJson(res, response);
    }
}
